import React from 'react'
import { Button } from 'antd'
import { SchemaForm, Item, Submit, ErrorList, Layout, SchemaType } from '@amazebird/antd-schema-form'

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 }
  }
}

const data = {
  users: [{
    name: '易烊千玺',
    age: 20
  }, {
    name: '王大锤',
    age: 32
  }]
}

const schema: SchemaType = {
  users: {
    type: 'array',
    label: '用户',
    rules: [{
      validator: async (_, names) => {
        if (!names || names.length < 2) {
          return Promise.reject(new Error('至少两名乘客'))
        }
      }
    }],
    item: {
      type: 'object',
      fields: {
        name: {
          label: '姓名',
          component: 'Input',
          required: true
        },
        age: {
          label: '年龄',
          component: 'InputNumber',
          required: true
        }
      }
    }
  }
}

function SimpleArrayForm () {
  const onClick = (formdata) => {
    console.info(formdata)
  }

  const onError = (errorInfos) => {
    console.error(errorInfos)
  }

  return (
    <SchemaForm schema={schema} initialValues={data} {...formItemLayout}>
      <Item field="users">
        {(fields, { add, remove }, { errors }) => {
          return (
            <>
              {
                fields.map((field) => {
                  const { key, ...restProps } = field
                  return (
                    <Item {...field} >
                      <div style={{ display: 'flex', alignItems: 'baseline' }} key={key}>
                        <Item field="name" required={false} />
                        <Item field="age" required={false} />
                        <Button onClick={() => { remove(field.name) }}>删除</Button>
                        <Button onClick={() => { add({}, field.index) }}>插入一行</Button>
                      </div>
                    </Item>
                  )
                })
              }
              <Button onClick={() => { add() }}>添加用户</Button>
              <ErrorList errors={errors} />
            </>
          )
        }
        }
      </Item>
      <Layout offset={8}>
        <Submit type="primary" onFinish={onClick} onError={onError}>确定</Submit>
      </Layout>

    </SchemaForm>
  )
}

export default SimpleArrayForm
